#!/bin/bash
#%depends: mount tuda_mount network nfs
#%provides: tuda_sync
#%programs: /usr/bin/rsync /usr/bin/ssh /usr/bin/tee /usr/bin/dialog /usr/bin/gawk /usr/bin/sed 
#%stage: filesystem
#Author: Geert Geurts, geert.geurts@hrz.tu-darmstadt.de
PATH="/lib/tuda/bin/:$PATH"
. /lib/tuda-lib.sh
[ "$debug" ]&&echo "tuda_sync: Running tuda_sync..."
PROVNODE="$(getarg provnode)"
IMAGE="$(getarg image|sed 's/\/$//')"
ROOT="$(getarg root)"
ROOTMNT=/root
INSTIF="$(getarg instif)"
IP="$(ip addr show dev $INSTIF 2>/dev/null|grep 'inet '|gawk '{print $2}'|gawk -F'/' '{print $1}')"
for MOUNTPOINT in $(while read P; do echo $P|gawk -F: '{print $1}'; done</tmp/partitions|sort); do
	if [ "$MOUNTPOINT" == "/" ]; then 
		continue	#root is already mounted..
	else
		if [ ! -d $ROOTMNT$MOUNTPOINT ]; then
			mkdir -p $ROOTMNT$MOUNTPOINT
		fi
		mount $(grep -e ^"$MOUNTPOINT:" /tmp/partitions|gawk -F: '{print $2}') $ROOTMNT$MOUNTPOINT||/bin/bash
	fi
done
while [ "$(/usr/bin/ssh -i /lib/tuda-id_rsa $PROVNODE /usr/lib/tuda/sync_status.sh $IP 2>/dev/null)" != "commit" ]; do
	echo "tuda_sync: Provision node seems busy... waiting"
	sleep 20
done
echo "tuda_sync: Whohooo... it's our turn"
sleep 3
busybox clear
rsync -e 'ssh -i /lib/tuda-id_rsa' -zxapSH -v --del  --exclude="/tmp/*" --exclude="/var/log/*" --exclude="/var/run/*" --progress $PROVNODE:$IMAGE/ /root 2>/dev/null|tee /root/var/log/tuda_rsyn.log|gawk -f /lib/rsync.awk | sed --unbuffered 's/\([0-9]*\).*/\1/' | dialog --stdout --ascii-lines --no-shadow --title "TUDA rsync-install" --gauge "Progress of rsync..." 10 100
/usr/bin/ssh -i /lib/tuda-id_rsa $PROVNODE /usr/lib/tuda/sync_done.sh $IP 2>/dev/null		#clean our ip from /var/spool/tuda_install.status
